package com.jingdianjichi.subject.application;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class MonkeyBanana {
    private static final int TOTAL_BANANAS = 100;
    private static final int MONKEY_COUNT = 3;

    private static int bananasLeft = TOTAL_BANANAS;
    private static Lock lock = new ReentrantLock();
    private static Condition condition = lock.newCondition();
    private static int nextMonkey = 0;

    public static void main(String[] args) {
        for (int i = 0; i < MONKEY_COUNT; i++) {
            new Thread(new Monkey(i)).start();
        }
    }

    static class Monkey implements Runnable {
        private int monkeyId;

        public Monkey(int monkeyId) {
            this.monkeyId = monkeyId;
        }

        @Override
        public void run() {
            while (true) {
                lock.lock();
                try {
                    while (monkeyId != nextMonkey) {
                        try {
                            condition.await();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }

                    if (bananasLeft > 0) {
                        bananasLeft--;
                        System.out.println("Monkey " + monkeyId + " 获取香蕉 剩余香蕉: " + bananasLeft);
                        nextMonkey = (nextMonkey + 1) % MONKEY_COUNT;
                        condition.signalAll();
                    } else {
                        break;
                    }
                } finally {
                    lock.unlock();
                }
            }
        }
    }
}